<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>测试</title>
    <style>
        .p {
            font-size: 24px;
            color: #ff0000;
        }

        .modifyFont {
            color: #ff0000;
            font-size: 36px;
            background-color: #ffff00;
            width: 300px;
            height: 60px;
        }
    </style>
</head>
<body>
    <h1>这是测试的标题1</h1>
    <p class="p">接收到的消息</p>
    <input type="text" class="info">
    <button class="send">向应用侧发送消息</button>

    <script>
        let webPort

        // 前端页面中注册 message 事件监听
        window.addEventListener('message', (event) => {
            if (event.data === '__init_port__') {
                // 接收到从应用侧发送到前端页面中的消息端口
                webPort = event.ports[0]

                // 通过消息端口，接收应用侧发送到前端页面的消息
                webPort.onmessage = (event) => {
                    if (typeof event.data === 'string') {
                        document.querySelector('.p').innerHTML = '接收到的消息:' + event.data
                    }
                }
            }
        })

        // 向应用侧发送消息
        document.querySelector('.send').onclick = () => {
            webPort?.postMessage(document.querySelector('.info').value)
        }
    </script>
</body>
</html>